const express = require(`express`)
const passport = require('passport');
const asyncHandler = require('express-async-handler');
const actionCtrl = require('../controllers/action.controller');

const router = express.Router()

router.use(passport.authenticate('jwt', { session: false }))

router.route('/').get(asyncHandler(getAll));
router.route('/').post(asyncHandler(add));
router.route('/').put(asyncHandler(edit));
router.route('/:id').get(asyncHandler(getOne));
router.route('/:id').delete(asyncHandler(remove));

// const path = require('path'); //系统路径模块
// const fs = require('fs'); //文件模块
// const action_json = path.join(path.resolve('./'), 'data/action.json'); 

async function getAll(req, res){
    const user = req.user
    const action = await actionCtrl.findAll(user)
    res.jsonp({ code: 20000, data: action })
}

async function getOne(req, res){
    let data = await actionCtrl.findOne(req.params.id);
    console.log(data)
    res.json({ code: 20000, data: data })
}

async function add(req, res){
    let action = await actionCtrl.insert(req.body);
    res.json({ code: 20000, message: '添加成功' })
}

async function remove(req, res){
    let err = await actionCtrl.remove(req.params.id);
    if (!err) {
        res.json({ code: -1, message: '删除失败' })
    }
    res.json({ code: 20000, message: '删除成功' })
}

async function edit(req, res){
    let err = await actionCtrl.edit(req.body)
    if (!err) {
        res.json({ code: -1, message: '修改失败' })
    }
    res.json({ code: 20000, message: '修改成功' })
}


module.exports = router